<template>
  <el-select v-model="value"
             :loading="loading"
             :placeholder="placeholder"
             :remote-method="handleRemoteMethod"
             clearable
             filterable
             remote
             reserve-keyword
             @change="handleValueChange"
             @clear="options = []">
    <el-option v-for="item in options" :key="item.id" :label="item.text" :value="item.label1">
      <template v-if="custom">
        <span style="float: left">{{ item.text }}</span>
        <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">{{ item.label1 }}</span>
      </template>
    </el-option>
  </el-select>
</template>

<script lang="ts" setup>

import { computed, ref } from 'vue';
import request from '@/utils/axios/axios-service.ts'
import { SelectItem } from '@/api';

defineOptions({name: 'select-remote'});

const props = defineProps({
  modelValue: {
    type: String,
  },
  apiUrl: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    default: '请输入关键词'
  },
  readonly: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 10
  },
  custom: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'change']);
const value = computed({
  get: () => props.modelValue,
  set: (val) => {

  },
});

// 远程数据
const options = ref<SelectItem[]>([])
const loading = ref(false)

/** 处理远程搜索 */
const handleRemoteMethod = (query: string) => {
  if (query) {
    loading.value = true;
    // 调用接口进行搜索
    request.get(props.apiUrl, {params: {search: query, limit: props.limit}}).then((res: any) => {
      options.value = res.data || [];
    }).finally(() => loading.value = false);
  } else {
    //options.value = []
  }
};

/** 对外提供方式 */
defineExpose({handleRemoteMethod});

/** 处理值变更事件 */
const handleValueChange = (val: any) => {
  emit('update:modelValue', val);
  if (val && val !== '') {
    let itemList = options.value.filter(item => item.label1 === val);
    emit('change', itemList.length > 0 ? itemList[0] : null);
  } else {
    emit('change', null);
  }
};

</script>

<style lang="scss" scoped>

</style>
